var selecttype;
var datatable;
var datatabletype = 0;
$(function(){
	selecttype = "rocketMQ";
	MQfiletype = "excel";
	$("#params").empty();
	$("#params").html($("#rocketMQ_params").html());
	$("#rocketMQ_params_2").show();
	setTimePicker($('#starttime'),tmpinputformat);
	$(document).bind("click",function(e){ 
		var target = $(e.target); 
		var id = target.attr('id'); 
		//点击触发事件，如果点击指定的元素那么弹出输入时间格式的控件，否则隐藏该控件
		if ($("#select2-drop").css("display") == 'none' && (id == 'timeformatspan' || id == 'timeformatalink' || id == 's2id_truck_id')) {
			alertsettimeformat();
		}
		else if(target.closest("#select2-drop").length == 0){ 
			$("#select2-drop").hide(); 
		}
	});
});
/**
 * 选择构造数据的类型：选择不同类型展示不同选择项
 */
function selectDataProviderType() {
	selecttype =  $("#selectTable").find("option:selected").text();
	if (selecttype == "rocketMQ") {
		$("#params").empty();
		$("#params").html($("#rocketMQ_params").html());
		$("#rocketMQ_params_2").show();
		setTimePicker($('#starttime'),tmpinputformat);
	}
	else if (selecttype == "mongoDB") {
		
	}
	else if (selecttype == "HBase") {
		$("#params").empty();
		$("#rocketMQ_params_2").hide();
		$("#params").html($("#HBase_params").html());
		var int1 = getHbases();
		if (int1 == 0) {
			var int2 = getTables();
			if (int2 == 0) {
				selectrowkey();
				settimeInternalpicker();
			}
		}
//		settimeInternalpicker();
	}
	else if (selecttype == "MQTT") {
	
	}
}
/**
 * 选择rowkey后初始化所有设置并加载html
 */
function selectrowkey() {
	$("#hbase_selectrowkey").show();
	$("#hbase_selectrowkey").html(getrowkeysearchstr());
	settimeInternalpicker();
}
/**
 * 导入数据：根据不同类型导入作不同处理
 */
function dataprovider_importData () {
	if (selecttype == "rocketMQ") {
		var nameServer =  $("#nameserver").val();
		var Topic =  $("#topic").val();
		var Imei =  $("#imei").val();
		var Tag =  $("#tag").val();
		var sheetname =  $("#importsheet").val();
		var starttime =  $("#starttime").val();
		var timeinternal =  $("#timeinternal").val();
		var sendinternal =  $("#sendinternal").val();		
		if (isStrEmpt(Tag)) {
			Tag = "*";
		}
		if (isStrEmpt(filename)) {
			dialog('notice','导入文件不能为空',3000);
		}
		else if (isStrEmpt(nameServer)) {
			dialog('notice','nameServer不能为空',3000);
		}
		else if (isStrEmpt(Topic)) {
			dialog('notice','topic不能为空',3000);
		}		
		else if (isStrEmpt(Imei)) {
			dialog('notice','imei不能为空',3000);
		}
		else {
			$("#doImport").attr('disabled',true);  
			dialog('loading','导入中...','');
			$.ajax({
				url : "/smarttest-frontstage/dataprovider/importRocketMQData.action",
				data : {nameserver:nameServer,topic:Topic,imei:Imei,tag:Tag,filename:filename,sheetname:sheetname,timeformat:tmpinputformat,starttime:starttime,timeInternal:timeinternal,sendInternal:sendinternal},
				method : 'GET',
				error:function(response,error){
					dialog('error','error'+response.status,3000);
					$("#doImport").attr('disabled',false);  
					}, 
				success : function(data) {
					if(data.status == 'succ') {
						if (datatabletype == 1) {
							   datatable.ajax.reload();
						   }
						else {
							   if (datatable != undefined) {
								   datatable.destroy();
							   }
							   var ths = $("#dt_basic > thead > tr");
							   $("#dt_basic > tbody").empty();
							   ths.html("<th style=\"width: 30%;text-align: center;\">消息入库时间</th>"+
										"<th style=\"width: 10%;text-align: center;\">offset</th>"+
										"<th style=\"width: 60%;text-align: center;\">message</th>");
							   datatable = convertDataTable_MQ();
							   datatabletype = 1; 			   
						 }
						datatabletype = 1;
						dialog('succ','导入成功',3000);
						$("#doImport").attr('disabled',false);  
					}
					else if(data.status == 'error'){
						dialog('error','导入失败',3000);
						$("#doImport").attr('disabled',false); 
					}
					
				}
			});
		}		
	}
	else if (selecttype == "mongoDB") {
		
	}
	else if (selecttype == "HBase") {
		
	}
	else if (selecttype == "MQTT") {
	
	}
}
/**
 * 数据构造：查询数据。
 */
function dataprovider_getData () {
	if (selecttype == "rocketMQ") {
		var nameServer =  $("#nameserver").val();
		var Topic =  $("#topic").val();
		var Imei =  $("#imei").val();
		if (isStrEmpt(nameServer)) {
			dialog('notice','nameServer不能为空',3000);
		}
		else if (isStrEmpt(Topic)) {
			dialog('notice','topic不能为空',3000);
		}
		else if (isStrEmpt(Imei)) {
			dialog('notice','imei不能为空',3000);
		}
		else {
			if (datatabletype == 1) {
				   datatable.ajax.reload();
			   }
			   else {
				   if (datatable != undefined) {
					   datatable.destroy();
				   }
				   var ths = $("#dt_basic > thead > tr");
				   $("#dt_basic > tbody").empty();
				   ths.html("<th style=\"width: 5%;text-align: center;\">消息入库时间</th>"+
							"<th style=\"width: 5%;text-align: center;\">offset</th>"+
							"<th style=\"width: 90%;text-align: center;\">message</th>");
				   datatable = convertDataTable_MQ();
				   datatabletype = 1; 			   
			 }
			datatabletype = 1;
		}
	}
	else if (selecttype == "mongoDB") {
		datatabletype = 2;
	}
	else if (selecttype == "HBase") {
		var ele = $("#hbase_selectrowkey > div").find("section");
		var jo = "{";
		var timestr = "\"time\":";
		var index = 0;
		var isValuesEmpty = false;
		for (var i = 0; i < ele.length; i++) {
			if (isContains(ele.eq(i).parent().attr('style'),"display: none")){
				continue;
			}
			else {
				var name = ele.eq(i).children('label').eq(0).text();
				var value = ele.eq(i).find('input').eq(0).val();
				if (value == null || value.replaceAll(" ","") == '') {
					isValuesEmpty = true;
					dialog('error',name+"不能为空",3000);
					break;
				}
				else {
					var id = ele.eq(i).find('input').eq(0).attr('id');
					if (id == 'Hbase_starttime') {
						if (index == 0) {
							timestr += "{\"start\":\""+value+"\"";
						}
						else {
							timestr += ",\"start\":\""+value+"\"}";
						}
						index++;
					}
					else if (id == 'Hbase_endtime') {
						if (index == 0) {
							timestr += "{\"end\":\""+value+"\"";
						}
						else {
							timestr += ",\"end\":\""+value+"\"}";
						}
						index++;
					}
					else if (id == 'rowkey_timestamp') {
						timestr = "\"time\":\"" + value + "\"";
					}
					else if (id == 'Hbase_exacttime') {
						timestr = "\"time\":\"" + value + "\"";
					}
					else {
						jo += "\""+name+"\":\""+value+"\",";
					}
				}				
			}
		}
		if (!isValuesEmpty) {
			jo += timestr+"}";
//			dialog('loading','查询中...','');
//			$.ajax({
//				url : "/smarttest-frontstage/dataprovider/getHbaseResult.action",
//				data : {searchstr:jo,tid:$("#htableselect").find("option:selected").val(),hid:$("#hbaseselect").find("option:selected").val()},
//				method : 'GET',
////				async:false,
//				error:function(response,error){
//					dialog('error','error'+response.status,3000);
//					}, 
//				success : function(data) {
//					$("#dt_basic").html(data.data);
//					dialog('succ','查询完毕',3000);
//				}
//			});
			if (datatabletype == 3) {
				   datatable.ajax.reload();
			   }
			   else {
				   if (datatable != undefined) {
					   datatable.destroy();
				   }
				   var ths = $("#dt_basic > thead > tr");
				   $("#dt_basic > tbody").empty();
				   ths.html("<th style=\"width: 30%;text-align: center;\">rowkey</th>"+
							"<th style=\"width: 10%;text-align: center;\">timestamp</th>"+
							"<th style=\"width: 10%;text-align: center;\">family</th>"+
							"<th style=\"width: 10%;text-align: center;\">qualifier</th>"+
							"<th style=\"width: 40%;text-align: center;\">value</th>");
				   datatable = convertDataTable_hbase(jo);
				   datatabletype = 3; 			   
			 }
		}
		
	}
	else if (selecttype == "MQTT") {
		datatabletype = 4;
	}
	
}
/**
 * 生成MQ的DataTable
 * @returns
 */
function  convertDataTable_MQ(){
	var ajax = {
	        "url": "/smarttest-frontstage/dataprovider/getRocketMQData.action",
	        "type": "GET",
	        "data": function(){
	     	   return {
	     		   "nameserver" : $("#nameserver").val(),
	     		  "topic" : $("#topic").val(),
	     		 "imei" : $("#imei").val(),
	     	    }
	        }
		};
		var aoColumnDefs = [
			];
		var columns = [
		               { "data": "mqstoragetime" },
		   				{ "data": "offset" },
		              { "data": "message" },
		          ];
		var initCompletefunc = function(){
	           $("#toolbar").append('<label><font color="red">查询结果最多显示最近的64条消息</font></label>');
	       };
	return convertDataTable_common($("#dt_basic"),ajax,aoColumnDefs,columns,initCompletefunc,true);
}
/**
 * 生成hbase的datatable
 * @param jo
 * @returns
 */
function  convertDataTable_hbase(jo){
	var ajax = {
	        "url": "/smarttest-frontstage/dataprovider/getHbaseResultNew.action",
	        "type": "GET",
	        "data": function(){
	     	   return {
	     		   "searchstr" : jo,
	     		  "tid" : $("#htableselect").find("option:selected").val(),
	     		 "hid" : $("#hbaseselect").find("option:selected").val(),
	     	    }
	        }
		};
		var aoColumnDefs = [
			];
		var columns = [
		               { "data": "rowkey" },
		   				{ "data": "timestamp" },
		              { "data": "family" },
		              { "data": "qualifier" },
		              { "data": "value" },
		          ];
		var initCompletefunc = "";
	return convertDataTable_common($("#dt_basic"),ajax,aoColumnDefs,columns,initCompletefunc,true);
}
var MQfiletype;
/**
 * 选择不同文件类型不同处理
 */
function selectFileType() {
	MQfiletype = $("#filetype").val();
	if (MQfiletype == "excel") {
		$("#sheetsection").show();
		$("#importMQdatafile").attr("accept","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel");
	}
	else if (MQfiletype == "txt") {
		$("#sheetsection").hide();
		$("#importsheet").html("");
		$("#importMQdatafile").attr("accept","text/plain");
	}
}
var filename;
/**
 * 上传MQ文件
 */
function mqUploadFile () {
		var form = $("form[name=importMQdata]");
		var options = {
			url : '/smarttest-frontstage/file/uploadMQwithuser.action',
			type : 'post',
			success : function(data) {
				filename = data.data;
				if (MQfiletype == "excel") {
					getsheets(filename);
				}
			}
		};
		form.ajaxSubmit(options);
		//$("#fileForm").submit();
}
function getsheets(fileName) {
	$.ajax({
		url : "/smarttest-frontstage/file/getsheets.action",
		data : {filename : fileName},
		method : 'GET',
		error:function(response,error){alert('error'+response.status);}, 
		success : function(data) {
			var html = data.data;
			$("#importsheet").empty();
			$("#importsheet").html(html);
		}
	});
}

var tmpinputformat = "yyyy-MM-dd HH:mm:ss";
/**
 * web页面设置时间格式
 */
function settimeformat () {
	var inputformat = $("#timeformattext").val();
	tmpinputformat = inputformat;
//	inputformat = inputformat.replaceAll("m", "i").replaceAll("M", "m");
//	if (isContains(inputformat,"h")) {
//		inputformat = inputformat.replaceAll("h", "H");
//	}
//	else if (isContains(inputformat,"H")) {
//		inputformat = inputformat.replaceAll("H", "h");
//	}
//	timeformat = inputformat;
	timeformat = setTimePicker($('#starttime'),inputformat);
	$("#timeformattext").val("");
	$("#timeformatspan").text(timeformat);
	$("#select2-drop").hide();
}
/**
 * 选择hbase的时间类型。时间段还是精确时间
 */
function selectTimetype() {
	var timetype =  $("#timetype").find("option:selected").val();
	if (timetype == 'timeinternal') {
		$("#hbase_type1").show();
		$("#hbase_type2").hide();
	}
	else if(timetype == 'exacttime') {
		$("#hbase_type1").hide();
		$("#hbase_type2").show();
	}
}
/**
 * 弹出设置时间格式框
 */
function alertsettimeformat () {
	$("#select2-drop").show();
	$("#timeformattext").focus();
}
var timeformat = 'yyyy-mm-dd hh:ii:ss';
/**
 *  hbase中选择hbase后初始化所有table
 */
function initTables(){
	var int2 = getTables();
	if (int2 == 0) {
		selectrowkey();
		settimeInternalpicker();
	}
}
